import { createRouter, createWebHistory } from 'vue-router';
import { routes } from './routes';
import { $auth } from '@/utils';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

export const isAuthorised = () => {
  return localStorage.getItem('General_Token') && Date.now() < +localStorage.getItem('tokenExpireTime') * 1000;
  // return true;
}

router.beforeEach((to, from, next) => {
  console.log(!isAuthorised());
  if (to.name !== 'Login' && !isAuthorised()) {
    next({ name: 'Login' });
  } else if (to.meta.roles) {
    const currentUserInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (currentUserInfo && $auth.hasRole(currentUserInfo.roleName, to.meta.roles)) {
      next();
    } else {
      console.error('用户没有权限访问该页面');
      next({ path: '/' });
    }
  } else {
    next();
  }
});

export default router
